﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using System.Diagnostics;
using ScriptLib = IWshRuntimeLibrary;

namespace StartSubMenu
{
    public partial class StartMenuManagerForm : Form
    {
        //--------------------------------------------------------------------------------
        public StartMenuManagerForm()
        {
            InitializeComponent();
        }
        //--------------------------------------------------------------------------------
        private void dgvItems_SelectionChanged(object sender, EventArgs e)
        {
            if (dgvItems.SelectedRows.Count > 0)
                btnAdd.Text = "Edit";
            else
                btnAdd.Text = "Add";
        }
        //--------------------------------------------------------------------------------
        private void LoadItems()
        {
            dgvItems.Rows.Clear();
            dgvItems.Columns.Clear();

            // no items
            if(!Directory.Exists("Items"))
                return;


            DataGridViewImageColumn colIcon = new DataGridViewImageColumn(true);
            colIcon.Name = "colIcon";
            colIcon.HeaderText = "Icon";
            dgvItems.Columns.Add( colIcon );
            int indexColName = dgvItems.Columns.Add("colName", "Name");
            dgvItems.Columns[indexColName].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

            
            string[] items = Directory.GetFiles("Items", "*.exe");

            foreach(string item in items)
            {
                FileInfo fi = new FileInfo(item);
                string lnkFullName = fi.FullName.ToLower().Replace(".exe", ".lnk");
                dgvItems.Rows.Add(new object[] { System.Drawing.Icon.ExtractAssociatedIcon(lnkFullName), fi.Name.Replace(fi.Extension, "") });
            }
        }
        //--------------------------------------------------------------------------------
        private void btnAdd_Click(object sender, EventArgs e)
        {
            AddSubMenuForm aesmf = new AddSubMenuForm();
            if (aesmf.ShowDialog() != DialogResult.OK)
                return;

            if (!Directory.Exists("Items"))
                Directory.CreateDirectory("Items");
            
            string targetExe = @".\Items\" + aesmf.Title + ".exe";
            string absoluteTargetExe = new FileInfo(targetExe).FullName;
            string targetDirectory = Path.GetDirectoryName(absoluteTargetExe);

            // copy this file to Items folder
            System.IO.File.Copy(Application.ExecutablePath, targetExe, true);

            // execute it to register tasks
            Process.Start(targetExe);

            string targetLnk = string.Format(@"{0}\{1}.lnk", targetDirectory, aesmf.Title);
            ScriptLib.WshShell shell = new ScriptLib.WshShell();
            ScriptLib.IWshShortcut shortcut = (ScriptLib.IWshShortcut)shell.CreateShortcut(targetLnk);
            shortcut.TargetPath = absoluteTargetExe;
            shortcut.IconLocation = aesmf.IconPath;
            shortcut.Save();

            PinUnpin(targetLnk, true);

            LoadItems();
        }
        //--------------------------------------------------------------------------------
        private void btnRemove_Click(object sender, EventArgs e)
        {
            if (dgvItems.SelectedRows.Count == 0)
                return;

            string name = (string)dgvItems.SelectedRows[0].Cells["colName"].Value;
            string targetExe = string.Format(@".\Items\{0}.exe", name);
            string absoluteTargetExe = new FileInfo(targetExe).FullName;
            string targetDirectory = Path.GetDirectoryName(absoluteTargetExe);
            string targetLnk = string.Format(@"{0}\{1}.lnk", targetDirectory, name);
            string targetXml = string.Format(@"{0}\{1}.xml", targetDirectory, name);

            PinUnpin(absoluteTargetExe, false);
            System.IO.File.Delete(targetLnk);
            System.IO.File.Delete(targetExe);
            System.IO.File.Delete(targetXml);

            dgvItems.Rows.Remove(dgvItems.SelectedRows[0]);
        }
        //--------------------------------------------------------------------------------
        private static void PinUnpin(string filePath, bool pin)
        {
            if (!File.Exists(filePath)) throw new FileNotFoundException(filePath);

            // create the shell application object
            dynamic shellApplication = Activator.CreateInstance(Type.GetTypeFromProgID("Shell.Application"));

            string path = Path.GetDirectoryName(filePath);
            string fileName = Path.GetFileName(filePath);

            dynamic directory = shellApplication.NameSpace(path);
            dynamic link = directory.ParseName(fileName);

            dynamic verbs = link.Verbs();
            for (int i = 0; i < verbs.Count(); i++)
            {
                dynamic verb = verbs.Item(i);
                string verbName = verb.Name.Replace(@"&", string.Empty).ToLower();

                if ((pin && verbName.Equals("pin to start menu")) || (!pin && verbName.Equals("unpin from start menu")))
                    verb.DoIt();
            }

            shellApplication = null;
        }
        //--------------------------------------------------------------------------------
        private void StartMenuManagerForm_Load(object sender, EventArgs e)
        {
            LoadItems();
        }
        //--------------------------------------------------------------------------------
    }
}
